//
//  HMHomeTableViewController.swift
//  Weibo
//
//  Created by 黄亦寒 on 16/9/19.
//  Copyright © 2016年 HM. All rights reserved.
//

import UIKit
import YYModel

class HMHomeTableViewController: HMVisitorTableViewController {

    //创建首页对应的viewModel对象
    fileprivate lazy var statusListViewModel:HMStatusListViewModel = HMStatusListViewModel()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        if !isLogin {
            visitorView?.updateVisitorInfo(message: nil, imageName: nil)
        }else{
            //加载首页数据
            loadHomeData()
            //设置界面
            setUpTableView()
            setUpUI()
        }
        
       
    }

    private func setUpTableView() {
        //注册cell
        tableView.register(HMHomeTableViewCell.self, forCellReuseIdentifier: "cell")
        
        //自动计算行高
        tableView.rowHeight = UITableViewAutomaticDimension
        //预估行高
        tableView.estimatedRowHeight = 200
        //去掉分割线
        tableView.separatorStyle = .none
        //底部视图为上拉加载
        tableView.tableFooterView = pullUpView
        //下拉刷新
        //self.refreshControl = pullDownView
        //tableView.addSubview(pullDownView)
        tableView.addSubview(pullDownControl)
    }
    
    override func setUpUI() {
        if let nav = self.navigationController {
            //把tipLabel添加到导航栏下面
            nav.view.insertSubview(tipLabel, belowSubview: nav.navigationBar)
            //设置tipLabel与导航栏底部对齐
            //nav.navigationBar.frame.maxY()
            tipLabel.frame = CGRect(x:0,y:nav.navigationBar.frame.maxY - 35,width:nav.navigationBar.width,height:35)
            
            
        }
    }
    //加载首页数据的方法
    func loadHomeData() {
        //如果上拉加载开启动画的话就代表上拉加载，否则代表下拉刷新
        statusListViewModel.loadHomeData(isPullUp: pullUpView.isAnimating) { (isSuccess,message) in
            
            if !self.pullUpView.isAnimating {
                self.startAnimation(message: message)
            }
            
            //结束刷新
            self.endRefreshing()
            
            if isSuccess {
                //如果数据请求成功，就刷新列表
                self.tableView.reloadData()
            }
        }
        
    }
    
    //结束刷新的方法
    private func endRefreshing() {
        //无论数据是否请求成功都把上拉加载的动画取消掉,以进行下一次加载
        pullUpView.stopAnimating()
        //结束下拉刷新
        pullDownView.endRefreshing()
        //结束自定义下拉刷新
        pullDownControl.endRefreshing()
    }
    
    //上拉加载
    fileprivate lazy var pullUpView:UIActivityIndicatorView = {
        let view = UIActivityIndicatorView(activityIndicatorStyle:UIActivityIndicatorViewStyle.whiteLarge)
        view.color = UIColor.red
        return view
    }()
    
    //下拉刷新
    fileprivate lazy var pullDownView:UIRefreshControl = {
       let view = UIRefreshControl()
        //添加下拉刷新事件
        view.addTarget(self, action: #selector(pullDownRefreshAction), for: .valueChanged)
        return view
    }()
    
    //自定义下拉刷新控件
    fileprivate lazy var pullDownControl:HMRefreshControl = {
        let view = HMRefreshControl()
        //添加下拉刷新事件
        view.addTarget(self, action: #selector(pullDownRefreshAction), for: .valueChanged)
        return view
    }()
    
    //TipLabel
    private lazy var tipLabel:UILabel = {
        let label = UILabel(textColor:UIColor.white,fontSize:12)
        label.backgroundColor = UIColor.orange
        label.textAlignment = .center
        label.text = "没有加载到最新数据"
        //label的默认状态是隐藏
        label.isHidden = true
        return label
        
    }()
    
    //开启tipLabel动画
    private func startAnimation(message:String) {
        //判断是否正在执行动画，如果正在执行动画就不需要再次执行
        if tipLabel.isHidden == false {
            return
        }
        
        //执行到此说明tipLabel未开启动画
        tipLabel.text = message
        //显示label
        tipLabel.isHidden = false
        //往下偏移自身高度
        UIView.animate(withDuration: 1, animations: { 
            self.tipLabel.transform = CGAffineTransform(translationX: 0, y: self.tipLabel.height)
            }) { (_) in
                UIView.animate(withDuration: 1, animations: {
                    //回归原位
                    self.tipLabel.transform = CGAffineTransform.identity
                    }, completion: { (_) in
                        //动画执行完重新隐藏
                        self.tipLabel.isHidden = true
                })
        }
        
    }
    
    //下拉刷新的方法
    @objc private func pullDownRefreshAction() {
        loadHomeData()
    }

}

//数据源方法
extension HMHomeTableViewController {
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return statusListViewModel.statusList.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! HMHomeTableViewCell

        //获取cell对应的model
        let viewModel:HMStatusViewModel = statusListViewModel.statusList[indexPath.row]
        cell.statusViewModel = viewModel
        //取消cell的点击效果
        cell.selectionStyle = .none
        
        return cell
    }
    
    //判断显示的是否是最后一个cell
    override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        if indexPath.row == statusListViewModel.statusList.count - 1 && !pullUpView.isAnimating{
            //开启动画
            pullUpView.startAnimating()
            print("最后一个cell了")
            //上拉加载数据
            loadHomeData()
        }
    }
}
